import string
import urllib
import logging
import os

from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import users
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
from django.utils.translation import ugettext as _

from adrianremembersmeapp.adrianremembersme import AdrianRemembersMe
from models import *
from scoutwebapp import scoutwebsettings

def mainpage(request):
    arm = AdrianRemembersMe()
    oldurl = ''
    targetuser = ''
    pagemessage = ''
    page = ''
    if request.COOKIES.has_key('ack'): #if we have cookies, get the member
        member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))
        if member: #if we have a logged in member
            name=member.name
            pagemessage = "Welcome "+name
            if member.group!='guest':
                page = 'mainmemberpage.html'
        else: #not logged in
            name = ""
            targetuser = ''
            oldurl = '/'
            pagemessage = 'Welcome to the %s site!  Please log in.' %(scoutwebsettings.TROOP_NAME)
            page = ''
    else: #no cookie = not logged in
        name = ""
        pagemessage = 'Please log in to view this page.'
        page = 'login.html'
    # display the page
    template_values = {
        'oldurl':oldurl,
        'troopname':scoutwebsettings.TROOP_NAME,
        'status': '',
        'targetuser':targetuser,
        'district':scoutwebsettings.TROOP_DISTRICT,
        'page':page,
        'pagemessage':pagemessage,
        'user':name,
        'login_url': '/login',
        'logout_url': '/logout'
    }
    return render_to_response("template.html",template_values)

def AddAnnouncement(request):
    arm = AdrianRemembersMe()
    oldurl = ''
    targetuser = ''
    pagemessage = ''
    page = ''
    form = ''
    if request.method == "GET":
        if request.COOKIES.has_key('ack'): #if we have cookies, get the member
            member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))
            if member: #if we have a logged in member
                name=member.name
                if member.group=='admin' or member.group=='dev':
                    page = 'AddAnnouncment.html'
                    form = AnnouncementForm
                else:
                    pagemessage = 'You do not have the required permissions to add announcements'
            else: #not logged in
                name = ""
                targetuser = ''
                oldurl = '/'
                pagemessage = 'Welcome to the %s site!  Please log in.' %(scoutwebsettings.TROOP_NAME)
                page = ''
        else: #no cookie = not logged in
            name = ""
            pagemessage = 'Please log in to view this page.'
            page = 'login.html'
    if request.method == 'POST':
        null
    # display the page
    template_values = {
        'oldurl':oldurl,
        'troopname':scoutwebsettings.TROOP_NAME,
        'status': '',
        'targetuser':targetuser,
        'district':scoutwebsettings.TROOP_DISTRICT,
        'page':page,
        'pagemessage':pagemessage,
        'user':name,
        'login_url': '/login',
        'logout_url': '/logout',
        'form': form
    }
    return render_to_response("template.html",template_values)



def logout(request):
    # todo: function to deliver cookieval
    arm = AdrianRemembersMe()
    response = HttpResponseRedirect("/")
    
    if request.COOKIES.has_key('ack'):
        cookieval = urllib.unquote(request.COOKIES['ack'])
        #empty cookie
        # todo: parametrize expiry date et al?
        
        #empty login from db
        arm.logincookieclear(cookieval)
        
        response.set_cookie('ack', "", expires="Fri, 31-Dec-2030 23:59:59 GMT")
        template_values = {
            'previously': ''
            }
        return render_to_response('loggedout.html', template_values)
    else:
        template_values = {
            'previously': true
            }
        
        return render_to_response('loggedout.html', template_values)

def login(request):
    # todo - set global OrgName value for application
    page = 'login.html'
 
    arm = AdrianRemembersMe()
    if request.method == "GET":
        
        if request.REQUEST.has_key('oldulr'):
            oldurl = request.REQUEST['oldurl']
        else:
            oldurl = "/"
        
        template_values = { 'oldurl': oldurl,
                            'OrgName': 'Troop249',
                            'troopname':scoutwebsettings.TROOP_NAME,
                            'status': '',
                            'pagemessage':'',
                            'page':page
                        }
        if request.REQUEST.has_key('errormsg'):
            template_values['errormsg'] = "Bad e-mail/password combination"
            
        return render_to_response("template.html", template_values)
    elif request.method == "POST":
        # check if pwd ok, look up user by username

        error = False
        oldurl = ""
        cookie = ""
        
        try:
            membername = request.REQUEST['name']
            password = request.REQUEST['password']
                
            if request.REQUEST.has_key('oldurl'):
                oldurl = request.REQUEST['oldurl']
            else:
                oldurl = "/"
                            
        except KeyError:
            error = True
        
        response = None
        
        if error:
            response = HttpResponseRedirect("/login?" + urllib.urlencode({"oldurl":oldurl, "error":error}, False))
        else:
            response = HttpResponseRedirect(oldurl)
            arm.memberlogin(response, membername, password, request.REQUEST.has_key('rememberme'))
    return response
   
   
        
def admin_user(request):
    arm = AdrianRemembersMe()
    oldurl = ''
    targetuser = ''
    pagemessage = ''
    page = ''
    if request.COOKIES.has_key('ack'): #if we have cookies, get the member
        member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))
        if member: #if we have a logged in member
            name=member.name
            if ((member.group == 'dev') or (member.group=='admin')):  #does he have permissions
                if request.REQUEST.has_key('user'):
                    targetuser = request.REQUEST['user']
                    oldurl = '/admin_user?user='+targetuser
                    mem = db.GqlQuery("SELECT * FROM Member WHERE name = :1 LIMIT 1", targetuser)
                    if mem.count(): #if the user to be modified is in the database
                        if request.method == "GET": # show the form
                            page = 'admin_user_page.html'
                        elif request.method == "POST": # if the form returns
                            if request.REQUEST.has_key('group'): # and has a valid value
                                group = request.REQUEST['group']
                                m = mem.get()  
                                m.group = group
                                db.put(m)
                                pagemessage = targetuser + ' has been placed in the '+group+' group.'
                            else:
                                pagemessage = 'You have reached this page in error please try again.'
                    else: #target user is not in database
                        pagemessage = 'Invalid user name.  Please verify that '+targetuser+' is a current member.'
                        page = ''
                else:#request does not list a target user
                    pagemessage = "You have reached this page in error please press home to return to the main page"    
                    page = ''
            else: #not an administrator
                pagemessage = "You do not have sufficient priveleges to view this page.  Please contact your administrator to request additonal privelges if required."
                page = ''
        else: #not logged in
            name = ""
            if request.REQUEST.has_key('user'):
                targetuser = request.REQUEST['user']
                oldurl = '/admin_user?user='+targetuser
                pagemessage = 'Please log in to view this page.'
                page = 'login.html'
            else:
                targetuser = ''
                oldurl = '/'
                pagemessage = 'You have reached this page in error, please return to the home page and log in to acess this site.'
                page = ''
    else: #no cookie = not logged in
        name = ""
        if request.REQUEST.has_key('user'):
            targetuser = request.REQUEST['user']
            oldurl = '/admin_user?user='+targetuser
            pagemessage = 'Please log in to view this page.'
            page = 'login.html'
        else:
            targetuser = ''
            oldurl = '/'
            pagemessage = 'You have reached this page in error, please return to the home page and log in to acess this site.'
            page = ''
    # display the page
    template_values = {
        'oldurl':oldurl,
        'troopname':scoutwebsettings.TROOP_NAME,
        'status': '',
        'targetuser':targetuser,
        'district':scoutwebsettings.TROOP_DISTRICT,
        'page':page,
        'pagemessage':pagemessage,
        'user':name,
        'login_url': '/login',
        'logout_url': '/logout'
    }
    return render_to_response("template.html",template_values)



def member(request):
    name = ''
    oldurl = ''
    targetuser = ''
    pagemessage = ''
    page = ''
    page = "member.html"
    arm = AdrianRemembersMe()
    if request.method == "GET":
        name = ''
        if request.COOKIES.has_key('ack'): #if we have cookies, get the member
            member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))
            if member: #if we have a logged in member
                name=member.name
        template_values = {
            'troopname':scoutwebsettings.TROOP_NAME,
            'ALLOW_PHOTO':scoutwebsettings.ALLOW_PHOTO,
            'page':page,
            'troopname':scoutwebsettings.TROOP_NAME,
            'district':scoutwebsettings.TROOP_DISTRICT,
            'user':name,
            'login_url': '/login',
            'logout_url': '/logout'
            }
        
        if request.COOKIES.has_key('ack'):
            template_values['name'] = request.COOKIES['ack']

        return render_to_response("template.html", template_values)
    
    elif request.method == "POST":
        arm = AdrianRemembersMe()
        
        errcode = arm.ERROR_OK
        errmsg = ""
        cookie = ""
        
        template_values = {
            'troopname':scoutwebsettings.TROOP_NAME,
            }
        
        try:
            tname = string.strip(request.REQUEST['name'])
            temail = string.strip(request.REQUEST['email'])
            tpassword = string.strip(request.REQUEST['password'])
    
            if (request.FILES.has_key('file') and request.FILES['file'].name):
                filedata = request.FILES['file'].read()
                filename = request.FILES['file'].name
                errcode = arm.membercreate(tname, tpassword, tname, temail, filedata, filename)
            else:
                errcode = arm.membercreate(tname, tpassword, tname, temail)
                
            if errcode != arm.ERROR_OK:
                if errcode == arm.ERROR_EMAIL_BAD:
                    errmsg = "bad email"    
                elif errcode == arm.ERROR_EMAIL_USED:
                    errmsg = "sorry, email already in use for another account"
                elif errcode == arm.ERROR_PASSWORD_WEAK:
                    errmgs = "password not long enough"
                elif errcode == arm.ERROR_USERNAME_NONE:
                    errmsg = "missing username"
                elif errcode == arm.ERROR_USERNAME_TAKEN:
                    errmsg = "username already taken, please try another"
                
            template_values['nameencoded'] = tname
            
        except KeyError:
            errmsg = "missing information"

        pagemessage = errmsg
        page= "memberprocess.html"
        template_values = {
            'oldurl':oldurl,
            'troopname':scoutwebsettings.TROOP_NAME,
            'status': '',
            'targetuser':targetuser,
            'district':scoutwebsettings.TROOP_DISTRICT,
            'page':page,
            'pagemessage':pagemessage,
            'user':name,
            'login_url': '/login',
            'logout_url': '/logout',
            'errmsg': errmsg
        }
        return render_to_response("template.html",template_values)

        response = render_to_response("memberprocess.html", template_values)            
        
        if errcode == arm.ERROR_OK:
            arm.memberlogin(response, tname, tpassword, request.REQUEST.has_key('rememberme'))
            
            mail.send_mail(sender=scoutwebsettings.SITE_DEV_MAIL,
                           to=scoutwebsettings.TROOP_ADMIN_MAIL,
                           subject="New account created",
                           body="""
Dear Scoutweb administrator,
  A new account has been created on """+scoutwebsettings.TROOP_NAME+""".  Please verify the account and select the appropriate permissions group if an upgrade is required.  All new accounts are created as guest members.  
  
  The new account username is """+tname+""" and the new user's email address is  """+temail+""".  
  This link will take you to the admin page for the new member:  http://"""+scoutwebsettings.SITE_NAME+"""/admin_user/?user="""+tname+"""
  This is an automatically generated email.  Please do not reply.
Thank you!""")                     
        return response
    
def memberlist(request):
    arm = AdrianRemembersMe()
    members = arm.membergetlist()
                
    template_values = {'memberlist':members}
            
    return render_to_response("memberlist.html", template_values)

def getimage(request):
    arm = AdrianRemembersMe()
    membername = request.REQUEST['member']
    mem = arm.memberget(membername)
    
    #Is this meant to be for single image or multiimage?
    if mem:
        for memphoto in mem.photo_set:
            if request.REQUEST.has_key('size') and request.REQUEST['size'] == "thumb":
                return HttpResponse(memphoto.thumb, mimetype="image/png")
            else:
                return HttpResponse(memphoto.content, mimetype="image/jpeg")

def logintest(request):
    arm = AdrianRemembersMe()
    member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))

    template_values = {}

    if member:
        template_values['name'] = member.name
    else:
        template_values['name'] = _("-- no member ") + request.COOKIES['ack']
        
    return render_to_response("logintest.html", template_values)

def changepassword(request):
    if request.method == "GET":
        # present form
        arm = AdrianRemembersMe()
        member = arm.membergetloggedin(urllib.unquote(request.COOKIES['ack']))

        template_values = {'name':member.name}
        
        return render_to_response("changepassword.html", template_values)
    elif request.method == "POST":
        # look up user;
        arm = AdrianRemembersMe()
        cookieval = urllib.unquote(request.COOKIES['ack'])
        member = arm.membergetloggedin(cookieval)
        
        template_values = {}
        
        if member:
            if arm.validatepassword(member,request.REQUEST['oldpassword']):
                if request.REQUEST['newpassword'] == request.REQUEST['newpasswordconfirm']:
                    arm.loginclearmember(member, cookieval)
                    newpassword = request.REQUEST['newpassword']
                    error = arm.memberchangepassword(member, newpassword)
                
                    if error == arm.ERROR_OK:
                        template_values['message'] = _("password changed")
                        
                else:
                    template_values['message'] = _("new password wasn't typed in right, please go back and fix.")
            else:
                template_values['message'] = _("old password wasn't right.")
        
        return render_to_response("changepasswordprocess.html", template_values) 

def forgotpassword(request):
    template = "forgotpassword.html"
    template_values = {}
        
    if request.method == "POST":
        memberemail = request.REQUEST['email']
        if memberemail == '':
            template_values['error'] = 'Please type in your email'
        
        else:
            arm = AdrianRemembersMe()
            resetpath = os.path.join(request.build_absolute_uri(),'resetpassword/')
            success = arm.forgotpassword(memberemail,resetpath)
            if success:
                template_values['success'] = 'True'
            else:
                template_values['error'] = 'The email you typed is not associated with an existing account.'
            
    return render_to_response(template, template_values)

def resetpassword(request,offset):
    template = "resetpassword.html"
    template_values = {}
    #Get Reset Code
    if request.method == "GET":
        code = offset
    elif request.method == "POST":
        code = request.REQUEST['code']
    #Validate Reset Code
    if code:
        arm = AdrianRemembersMe()     
        resetlink = arm.getresetlinkfromcode(code)
        if resetlink:
            template_values['code'] = code
            #Validate Form
            if request.method == "POST":
                password = request.REQUEST['password']
                password2 = request.REQUEST['password2']
                if password == '' or password != password2:
                    template_values['error'] = 'Please make sure passwords match and are not empty.'
                #Reset Password
                else:
                    success = arm.resetpassword(resetlink,password)
                    if success:
                        template_values['success'] = True
                    else:
                        template_values['error'] = 'There was an error while resetting your password. Please try again.'
                        
    return render_to_response(template, template_values)

def encryptpasswords(request):
    template = "encryptpasswords.html"
    template_values = {}
    
    arm = AdrianRemembersMe()
    success = arm.encryptpasswords()
    if success:
        template_values['message'] = 'Encryption succeeded. All passwords are now encrypted'
    else:
        template_values['message'] = '''Encryption failed. Make sure you have ENCRYPTED_PASSWORDS
        value set to True in adrianremembersmeapp/armsettings.py'''
    return render_to_response(template, template_values)
